import time
import random
import os
from datetime import datetime
from selenium import webdriver
# https://pypi.org/project/webdriver-manager/
from webdriver_manager.chrome import ChromeDriverManager
from fake_useragent import UserAgent


def time_watcher():
    print('--- %s seconds ---' % (time.time() - start_time))


def start_bot(browser, wallet):

    # обработка клика по кнопке BTC-кран
    time.sleep(get_time_await())
    # путь до кнопки
    path_button = '//*[@id="tab_bonus"]/a/span'
    browser.find_element_by_xpath(path_button).click()

    # вставляем номер BTC-кошелька в input
    time.sleep(get_time_await())
    browser.find_element_by_id('bonus_purse').send_keys(wallet)

    # обработка клика по кнопке "Получить бонус"
    time.sleep(get_time_await())
    browser.find_element_by_id('bonus_button').click()

    # обработка клика по квадратику "для проверки"
    time.sleep(10)
    path_check = '//*[@id="bonus_form"]/div[4]/div[1]'
    browser.find_element_by_xpath(path_check).click()

    # обработка повторного клика по кнопке "Получить бонус"
    time.sleep(5)
    browser.find_element_by_id('bonus_button').click()

    # закрываем Selenium
    time.sleep(get_time_await())
    get_data(browser)


def write_log(log, nameFile):  # запись log'a в файл
    path_f = os.path.dirname(os.path.abspath(__file__))
    with open(os.path.join(path_f, nameFile), "a", encoding='utf-8') as _file:
        _file.write(log)


def get_time_await():
    time_await = random.uniform(2, 4)
    print(f'time_await: {time_await}\n')
    return time_await


def get_data(browser):

    try:
        getted = browser.find_element_by_id(
            'bonus_stats').find_element_by_tag_name('b').get_attribute("title")
    except:
        getted = "None"
    try:
        balance = browser.find_element_by_id(
            'faucet_unpaid_balance').find_element_by_tag_name('b').get_attribute("title")
    except:
        balance = "None"

    now = datetime.now()
    data_time = now.strftime("%H:%M:%S %d-%m-%Y")

    write_log(
        f"{data_time} | getted: {getted} | balance: {balance}\n", "log.txt")


def setup_browser(proxy=None):

    # подмена UserAgent
    ua = UserAgent()
    # user_agent = ua.random
    user_agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36'

    # установка proxy
    if proxy != None:
        PROXY = proxy
        webdriver.DesiredCapabilities.CHROME['proxy'] = {
            "httpProxy": PROXY,
            "ftpProxy": PROXY,
            "sslProxy": PROXY,
            "proxyType": "MANUAL"}

    options = webdriver.ChromeOptions()
    options.add_argument(f"--user-agent={user_agent}")
    options.add_argument("--start-maximized")
    driver = webdriver.Chrome(chrome_options=options,
                              executable_path=ChromeDriverManager().install())

    return driver


def main():
    url = 'https://www.bestchange.ru/'
    proxy = 'http://175.106.18.201:38708'
    wallet = '3KBgUTDQWZDhMqBDqs2LCHwuQhYtDoY7KX'

    browser = setup_browser()
    browser.get(url)
    start_bot(browser, wallet)


if __name__ == '__main__':
    start_time = time.time()
    main()
    time_watcher()
